package droid.engine;

import android.view.*;
import android.content.*;
import android.graphics.*;
import java.util.*;

public class Panel extends SurfaceView implements SurfaceHolder.Callback {
	
	private GraphicsThread thread;
	private ArrayList<Entity> gameObjects;
	private long lastFrame = 0;
	private Bitmap bitmap;
	
	public Panel(Context context) {
		super(context);
		getHolder().addCallback(this);
		thread = new GraphicsThread(getHolder(), this);
		setFocusable(true);
		gameObjects = new ArrayList<Entity>();
		lastFrame = System.currentTimeMillis();
		bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
	}

	@Override
	public void onDraw(Canvas canvas) {
		long currentTime = System.currentTimeMillis();
		float deltaTime = (float)(currentTime - lastFrame) / 1000.0f;
		canvas.drawColor(Color.BLACK);
		synchronized (gameObjects) {
			for (Entity go : gameObjects)
				go.update(deltaTime);
			for (Entity go : gameObjects)
				go.draw(canvas);
		}
		lastFrame = currentTime;
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		
	}

	public void surfaceCreated(SurfaceHolder holder) {
		thread.setRunning(true);
		thread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		thread.setRunning(false);
		while (retry) {
			try {
				thread.join();
				retry = false;
			}
			catch (InterruptedException e) {
				
			}
		}
	}
	
	public boolean onTouchEvent(MotionEvent event) {
		Vector2 position = new Vector2(event.getX(), event.getY());
		AnEntity go = new AnEntity("GameObject", bitmap, position, null);
		synchronized (gameObjects) {
			gameObjects.add(go);
		}
		return true;
	}
}
